/** To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CopiaSeg.java
 *
 * Created on 07-may-2009, 21:18:43
 */

package laboratorio;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import oracle.toplink.essentials.ejb.cmp3.persistence.DirectoryArchive;

/**
 *
 * @author Juan Antonio Tirado
 */
public class CopiaSeg extends javax.swing.JFrame {
    //ATRIBUTOS
    private JFileChooser fc=new JFileChooser();
    private String newline = System.getProperty("line.separator");
    public File backupFile;

    /** Creates new form CopiaSeg */
    public CopiaSeg() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jButton3 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(laboratorio.LaboratorioApp.class).getContext().getResourceMap(CopiaSeg.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        jButton1.setFont(resourceMap.getFont("jButton1.font")); // NOI18N
        jButton1.setIcon(resourceMap.getIcon("jButton1.icon")); // NOI18N
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                salir(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("jPanel1.border.title"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, resourceMap.getFont("jPanel1.border.titleFont"), resourceMap.getColor("jPanel1.border.titleColor"))); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        jButton3.setFont(resourceMap.getFont("jButton3.font")); // NOI18N
        jButton3.setIcon(resourceMap.getIcon("jButton3.icon")); // NOI18N
        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backupActionPerformed(evt);
            }
        });

        jButton2.setFont(resourceMap.getFont("jButton2.font")); // NOI18N
        jButton2.setIcon(resourceMap.getIcon("jButton2.icon")); // NOI18N
        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                restoreActionPerformance(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jButton2)
                .addGap(22, 22, 22))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(20, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton1)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(12, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void salir(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_salir
        this.setVisible(false);
    }//GEN-LAST:event_salir

    private void backupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backupActionPerformed
        // TODO add your handling code here:
         fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
         fc.setToolTipText("Selección del directorio");
         fc.setDialogTitle("Selecciona el directorio deseado");
        int returnVal = fc.showOpenDialog(CopiaSeg.this);
         if (returnVal == JFileChooser.APPROVE_OPTION) {
             //Date d=new Date();
            // backupFile = new File(String.valueOf(fc.getCurrentDirectory()) + "\\lpd"+d+".sql");             
             File file = fc.getSelectedFile();
                try {
                    backup(file);
                } catch (IOException ex) {
                    Logger.getLogger(CopiaSeg.class.getName()).log(Level.SEVERE, null, ex);
                } catch (Exception ex) {
                    Logger.getLogger(CopiaSeg.class.getName()).log(Level.SEVERE, null, ex);
                }
              
         } 

}//GEN-LAST:event_backupActionPerformed

    private void restoreActionPerformance(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_restoreActionPerformance
        // TODO add your handling code here:
            int returnVal = fc.showOpenDialog(CopiaSeg.this);
             fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                try {
                restore(file);
                } catch (IOException ex) {
                    Logger.getLogger(CopiaSeg.class.getName()).log(Level.SEVERE, null, ex);
                } catch (Exception ex) {
                    Logger.getLogger(CopiaSeg.class.getName()).log(Level.SEVERE, null, ex);
                }
                //DirectoryArchive dir=//this is where a real application would open the file.
            }


}//GEN-LAST:event_restoreActionPerformance

  public void transfer(InputStream input, OutputStream output) throws Exception {
  byte[] buf = new byte[1024];
  int len;

  while ((len = input.read(buf)) > 0) {
    output.write(buf, 0, len);
  }
  input.close();
  output.close();
}


public void backup(File file) throws IOException, Exception{
    Date d=new Date();
    String s=String.valueOf(d.getDate()).concat(String.valueOf(d.getMonth()+1)).concat(String.valueOf(d.getYear()+1900));
    Runtime rt=Runtime.getRuntime();
    String command = "C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\mysqldump --opt --password= --user=root -h localhost lpd";// > "+file+"\\lpd"+s+".sql";
    Process child = rt.exec(command);

    InputStream input = child.getInputStream();

    FileOutputStream output = new FileOutputStream(file+"\\lpd"+s+".sql");
    transfer(input, output);

}

public void restore(File file) throws IOException, Exception{
    String command ="\"C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\mysql.exe\" --password= --user=root -h localhost lpd";// < \""+file+"\"";
    System.out.println(command);
    Process child = Runtime.getRuntime().exec(command);

    OutputStream output = child.getOutputStream();
    transfer(new FileInputStream(file),output);
    InputStream input = child.getInputStream();
    transfer(input, System.out); // escribimos el resultado en el System.out

}



    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CopiaSeg().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration//GEN-END:variables

}
